package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"maya-service/bll"
	"maya-service/model"
	"maya-service/server/web/middleware"
	"maya-service/utils"
)

var GameLevel = &gameLevel{}

func init() {
	RegisterRouter(GameLevel)
}

type gameLevel struct{}

// Init
func (a *gameLevel) Init(r *gin.RouterGroup) {
	g := r.Group("/gameLevel", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}
}

// create
func (a *gameLevel) create(c *gin.Context) {
	var (
		in  = &model.GameLevelCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.GameLevel.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// update
func (a *gameLevel) update(c *gin.Context) {
	var (
		in  = &model.GameLevelUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if len(in.StarZones) > 0 && (in.StarZone == nil || *in.StarZone == "") {
		data, _ := json.Marshal(in.StarZones)
		strData := string(data)
		in.StarZone = &strData
	}

	if err = bll.GameLevel.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

// list
func (a *gameLevel) list(c *gin.Context) {
	var (
		in  = &model.GameLevelListRequest{}
		out = &model.GameLevelListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.GameLevel.List(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	for i := 0; i < len(out.List); i++ {
		json.Unmarshal([]byte(out.List[i].StarZone), &out.List[i].StarZones)
	}
	utils.ResponseOk(c, out)
}

// list
func (a *gameLevel) find(c *gin.Context) {
	var (
		in  = &model.GameLevelInfoRequest{}
		out = &model.GameLevelInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if out, err = bll.GameLevel.Find(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}

	if out.Id > 0 {
		json.Unmarshal([]byte(out.StarZone), &out.StarZones)
	}
	utils.ResponseOk(c, out)
}

// delete
func (a *gameLevel) delete(c *gin.Context) {
	var (
		in  = &model.GameLevelDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.GameLevel.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
